package cn.surveyking.server.api;

import cn.surveyking.server.core.constant.AppConsts;
import cn.surveyking.server.core.constant.ErrorCode;
import cn.surveyking.server.core.exception.ErrorCodeException;
import cn.surveyking.server.core.security.JwtTokenUtil;
import cn.surveyking.server.domain.dto.*;
import cn.surveyking.server.service.SystemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;

/**
 * 门户认证
 * @author 刘海
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("${api.prefix}/portal")
public class PortalApi {

    private final RestTemplate restTemplate;

    private final JwtTokenUtil jwtTokenUtil;

    private final SystemService systemService;

    private static final String ENCRYPTION_URL = "http://bgtx.xstl.chnenergy.com.cn/pamsbsm/rest/API/AesUtsl/encrypt"; // 门户鉴权URL

    // 鉴权
   @GetMapping("/authentication")
    public ResponseEntity authentication(HttpServletRequest request) {
       // System.out.println(request.getParameter("token"));
       String token= request.getParameter("token");
       String userName= request.getParameter("userName");

       String userId= request.getParameter("userId");

       // return  null;
       // 1. 构建加密请求的Body
//        HashMap<String, String> map = new HashMap<>();
//        map.put("token", request.getParameter("token"));
//        // 2. 发送加密请求
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        HttpEntity<HashMap<String, String>> entity = new HttpEntity<>(map, headers);
        try {
            // 调用加密接口
//            ResponseEntity<EncryptResponse> encryptResponseEntity = restTemplate.exchange(
//                    ENCRYPTION_URL,
//                    HttpMethod.POST,
//                    entity,
//                    EncryptResponse.class
//            );
//            // 3. 处理加密响应
//            if (encryptResponseEntity.getBody() == null || encryptResponseEntity.getBody().getCode() != 1) {
//                // 加密失败的处理
//                throw new ErrorCodeException(ErrorCode.ValidationError);
//            }
//            String encryptedText = encryptResponseEntity.getBody().getEncryptedText();

            //根据用户编号查询用户信息
            UserInfo user=new UserInfo();
            user.setUserId(userId);
            if(user==null){
                throw new ErrorCodeException(ErrorCode.ValidationError);
            }
            HttpCookie cookie = ResponseCookie
                    .from(AppConsts.TOKEN_NAME, jwtTokenUtil.generateAccessToken(new UserTokenView(user.getUserId())))
                    .path("/").httpOnly(true).build();
            return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString())
                    .header(HttpHeaders.AUTHORIZATION,
                            jwtTokenUtil.generateAccessToken(new UserTokenView(user.getUserId())))
                    .build();
        } catch (Exception e) {
            // 异常处理
            throw new ErrorCodeException(ErrorCode.ValidationError);
        }
    }
}
